package com.xgggh.redpack.ui.map;

import android.Manifest;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import androidx.appcompat.widget.SearchView;
import androidx.core.view.MenuItemCompat;
import androidx.databinding.DataBindingUtil;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.Poi;
import com.baidu.mapapi.CoordType;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.xgggh.redpack.R;
import com.xgggh.redpack.base.ui.BaseActivity;
import com.xgggh.redpack.databinding.ActivityMapBinding;
import com.xgggh.redpack.domain.map.MapBinding;

import java.util.List;

public class MapActivity extends BaseActivity implements BDLocationListener,OnGetGeoCoderResultListener {
    ActivityMapBinding mBinding;
    MapBinding mapBinding = new MapBinding();
    // 定位相关
    LocationClient mLocClient;

    private int mCurrentDirection = 0;
    private double mCurrentLat = 0.0;
    private double mCurrentLon = 0.0;
    private float mCurrentAccracy;
    private MyLocationData locData;
    boolean isFirstLoc = true; // 是否首次定位

    private static final int ACCESS_FINE_LOCATION=404;
    private static final int ACCESS_COARSE_LOCATION=405;

    BitmapDescriptor locationMarker = BitmapDescriptorFactory
            .fromResource(R.drawable.location);

    GeoCoder  mSearch;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding= DataBindingUtil.setContentView(this,R.layout.activity_map);
        setSupportActionBar(mBinding.toolbar.toolbar);
        //mBinding.setVariable()
        mBinding.setMap(mapBinding);
       /* boolean pl=mayRequestPermissions(Manifest.permission.ACCESS_FINE_LOCATION,ACCESS_FINE_LOCATION);
        if (pl){
           boolean aa= mayRequestPermissions(Manifest.permission.ACCESS_COARSE_LOCATION,ACCESS_COARSE_LOCATION);
            if (aa){
                initMap();
            }
        }*/
        initGeoCode();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==ACCESS_FINE_LOCATION && resultCode==RESULT_OK){
            initMap();
        }else if (requestCode==ACCESS_COARSE_LOCATION && resultCode==RESULT_OK){
            initMap();
        }
    }

    private void initMap(){
        // 开启定位图层
        mBinding.contentMap.map.getMap().setMyLocationEnabled(true);
        mBinding.contentMap.map.getMap().setOnMapClickListener(new BaiduMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                mapBinding.setAddress("");

                mBinding.contentMap.map.getMap().setMyLocationEnabled(false);
                MarkerOptions marker = new MarkerOptions().position(latLng).icon(locationMarker);
                mBinding.contentMap.map.getMap().clear();
                mBinding.contentMap.map.getMap().addOverlay(marker);
                mapBinding.setLocation(latLng.latitude+","+latLng.longitude);
                //geoCode
                mSearch.reverseGeoCode(new ReverseGeoCodeOption().location(latLng).newVersion(1).radius(500));
            }

            @Override
            public boolean onMapPoiClick(MapPoi mapPoi) {

                mBinding.contentMap.map.getMap().setMyLocationEnabled(false);
                mapBinding.setAddress(mapPoi.getName());
                mapBinding.setLocation(mapPoi.getPosition().latitude+","+mapPoi.getPosition().longitude);

                MarkerOptions marker = new MarkerOptions().position(mapPoi.getPosition()).icon(locationMarker);
                mBinding.contentMap.map.getMap().clear();
                mBinding.contentMap.map.getMap().addOverlay(marker);
                return false;
            }
        });


        // 定位初始化
        mLocClient = new LocationClient(getApplicationContext());
        mLocClient.registerLocationListener(this);
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true); // 打开gps
        option.setCoorType(CoordType.BD09LL.name()); // 设置坐标类型
        option.setScanSpan(1000);
        option.setAddrType("all");
        mLocClient.setLocOption(option);
        mLocClient.start();
    }


    private void initGeoCode(){
        mSearch = GeoCoder.newInstance();
        mSearch.setOnGetGeoCodeResultListener(this);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.search, menu);
        MenuItem item = menu.findItem(R.id.action_search);
        SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);
        //设置搜索栏的默认提示
        //searchView.setQueryHint("请输入商品名称");
        //默认刚进去就打开搜索栏
        //searchView.setIconified(false);
        //设置输入文本的EditText
        //SearchView.SearchAutoComplete et = searchView.findViewById(R.id.search_src_text);
        //设置搜索栏的默认提示，作用和setQueryHint相同
        //et.setHint("输入商品名或首字母");
        //设置提示文本的颜色
        //et.setHintTextColor(Color.WHITE);
        //设置输入文本的颜色
        //et.setTextColor(Color.WHITE);
        //设置提交按钮是否可见
        searchView.setSubmitButtonEnabled(false);

        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                Toast.makeText(MapActivity.this, "您输入的文本为" + query, Toast.LENGTH_SHORT).show();
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                return false;
            }
        });
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 退出时销毁定位
        if (mLocClient!=null){
            mLocClient.stop();
        }
        // 关闭定位图层
        mBinding.contentMap.map.getMap().setMyLocationEnabled(false);
        mBinding.contentMap.map.onDestroy();
        mSearch.destroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mBinding.contentMap.map.onResume();
    }


    @Override
    protected void onPause() {
        super.onPause();
        mBinding.contentMap.map.onPause();
    }

    @Override
    public void onReceiveLocation(BDLocation location) {
        // map view 销毁后不在处理新接收的位置
        if (location == null || mBinding.contentMap.map == null) {
            return;
        }
        String address=location.getCity()+location.getDistrict()+location.getStreet()+location.getStreetNumber();

        mapBinding.setAddress(address);
        mapBinding.setAddressPOI(location.getAddress().address);
        mCurrentLat = location.getLatitude();
        mCurrentLon = location.getLongitude();

        mapBinding.setLocation(mCurrentLat+","+mCurrentLon);

        mCurrentAccracy = location.getRadius();
        locData = new MyLocationData.Builder()
                .accuracy(location.getRadius())
                // 此处设置开发者获取到的方向信息，顺时针0-360
                .direction(mCurrentDirection).latitude(location.getLatitude())
                .longitude(location.getLongitude()).build();
        mBinding.contentMap.map .getMap().setMyLocationData(locData);
        if (isFirstLoc) {
            isFirstLoc = false;
            LatLng ll = new LatLng(location.getLatitude(),
                    location.getLongitude());
            MapStatus.Builder builder = new MapStatus.Builder();
            builder.target(ll).zoom(18.0f);
            mBinding.contentMap.map.getMap().animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
        }
    }


    @Override
    public void onGetGeoCodeResult(GeoCodeResult geoCodeResult) {

    }

    @Override
    public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) {
        if (reverseGeoCodeResult == null || reverseGeoCodeResult.error != SearchResult.ERRORNO.NO_ERROR) {
            Toast.makeText(MapActivity.this, "抱歉，未能找到结果", Toast.LENGTH_LONG).show();
            return;
        }
        mapBinding.setAddress(reverseGeoCodeResult.getAddress());
        Toast.makeText(MapActivity.this, reverseGeoCodeResult.getAddress() + " adcode: " + reverseGeoCodeResult.getAdcode(), Toast.LENGTH_LONG).show();
    }
}
